<?php

###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ################

class JFX_Module_Blockstyle extends JFX_Module {

	public $keyname = 'blockstyle';
	public $title = 'Block style';
	public $version = '0.2.9';
	public $dependencies = array(
	    array(
		'keyname' => 'imager',
		'version' => '0.2.9'
	    )
	);
	public $browserVersions = array('lt IE 6', 'IE 6', 'lt IE 7', 'IE 7', 'lt IE 8', 'IE 8');

	public function __construct() {
		parent::__construct();
		//$this->resetLanguages();
		$this->title = $this->lang('module_title');
	}

	public function blockHasClassname($block, $classname) {
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');

		if ($DB->countRows($CONFIG->dbprefix . $this->keyname . '_classnames_to_blocks', "block_id='{$block->id}' AND classname = '{$classname}'") > 0) {
			return true;
		}

		if ($DB->countRows($CONFIG->dbprefix . $this->keyname . '_classnames_to_blocks', "block_id='{$block->details['template_id']}' AND classname = '{$classname}'") > 0) {
			return true;
		}

		return false;
	}


	public function getBlockClassnamesAsArray($blockid, $withHandler=false){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$blockid = $DB->escape($blockid);
		$allClassnames = $DB->fetchAll("SELECT classname FROM {$CONFIG->dbprefix}{$this->keyname}_classnames_to_blocks WHERE block_id = '{$blockid}'");
		if($withHandler){
			foreach($allClassnames as $k=>$row){
				$allClassnames[$k]['handler'] = $this->getHandler($row['classname']);
			}
		}
		return $allClassnames;
	}

	public function addClassname($blockid, $classname){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$safeBlockid = $DB->escape($blockid);
		$safeClassname = $DB->escape($classname);
		$dbParams = array(
		    'block_id'=>$blockid,
		    'classname' => $classname
		);
		if($DB->countRows($CONFIG->dbprefix.$this->keyname.'_classnames_to_blocks', "block_id = '{$safeBlockId}' AND classname = '{$safeClassname}'")==0){
			// insert
			$DB->insert($CONFIG->dbprefix.$this->keyname.'_classnames_to_blocks', $dbParams);
		}
	}

	public function getAllClassnamesAsArray($withHandler=false) {
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$handler = '';
		$allClassnames = $DB->fetchAll("SELECT classname FROM {$CONFIG->dbprefix}{$this->keyname}_classnames ORDER BY sorting ASC");

		foreach ($allClassnames as $k => $row) {
			$allClassnames[$k]['title'] = $this->getContentLang('title', $row['classname']);
			if ($withHandler) {
				$allClassnames[$k]['handler'] = $this->getHandler($row['classname']);
			}
		}

		if ($withHandler) {
			foreach ($allClassnames as $k => $row) {
				$handler = $this->getHandler($row['classname']);
				$allClassnames[$k]['handler'] = $handler;
			}
		}
		return $allClassnames;
	}

	public function getClassnameTitle($classname) {
		return $this->getContentLang('title', $classname);
	}

	public function saveBlockCss($blockId, $css='') {
		// delete all existing files to recache calculated CSS
		$allFiles = JFX_Data::getModuleFilesByPrefix($this->keyname, 'css');
		foreach($allFiles as $k=>$file){
			$file->delete();
		}

		$file = JFX_Data::getFile('css', $blockId . '.txt', $this->keyname);
		if (!is_object($file) || false == ($file instanceof JFX_Data_File)) {
			$CONFIG = JFX::registry('config');
			$filepath = $CONFIG->tmpDir . '/' . $this->keyname . '/' . $blockId . '.txt';
			$fh = fopen($filepath, 'w');
			fwrite($fh, $css);
			fclose($fh);
			$file = JFX_Data::newFile($this->keyname, $filepath, JFX_Block::getTitleById($blockId), 'css');
			$file->save();

		} else {
			$file->setContents($css);
			$file->save();
		}
	}

	public function getBlockCss($block, $withUrl=true, $forceRefresh=false) {
		$IMAGE_MODULE = JFX::registry('JFX_Module_Imager');
		$file = JFX_Data::getFile('css', $block->id . '.txt', $this->keyname);
		if ($forceRefresh || !is_object($file) || false === ($file instanceof JFX_Data_File)) {
			$doneStyles = array();
			$this->saveBlockCss($block->id, JFX_Module_Blockstyle_Handler::getBlockCss($block, $doneStyles));

			return $this->getBlockCss($block, $withUrl);
		}
		$returnString = $file->getContents();
		if ($withUrl) {
			$returnString = str_replace(':|imageUrl|:', $IMAGE_MODULE->imageUrl . '/serve.php', $returnString);
		}
		return $returnString;
	}

	public function saveHandler($handler) {
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$file = JFX_Data::getFile('handlers', $handler->classname . '.txt', $this->keyname);

		if (!is_object($file) || !file_exists($file->getAbsolutePath())) {
			// let's start a new file
			if (!is_dir($CONFIG->tmpDir . '/' . $this->keyname)) {
				mkdir($CONFIG->tmpDir . '/' . $this->keyname);
			}
			$tmpname = $CONFIG->tmpDir . '/' . $this->keyname . '/' . $handler->classname . '.txt';
			$fh = fopen($tmpname, 'w');
			fwrite($fh, serialize($handler));
			fclose($fh);
			$file = JFX_Data::newFile($this->keyname, $tmpname, $handler->name, 'handlers');
		}

		//$file->setContents($handler->__toJson());
		$file->setContents(serialize($handler));
		$file->save();
	}

	public function getHandler($classname) {

		try {
			$obj = JFX::registry('JFX_Module_Blockstyle_Handler_' . $classname);
			if (is_object($obj) && $obj instanceof JFX_Module_Blockstyle_Handler) {
				return $obj;
			}
		} catch (Exception $e) {
			
		}

		$handlerImport = JFX_Data::getFile('handlers', $classname . '.txt', $this->keyname);
		
		$tempHandler = null;

		if(is_object($handlerImport) && $handlerImport instanceof JFX_Data_File){
			if (strlen(trim($handlerImport->getContents())) > 0) {
				$tempHandler = @unserialize($handlerImport->getContents());
			}
		}else{
			// there's no handler file! lets make the handler and save the file
			$handler = new JFX_Module_Blockstyle_Handler($classname);
			$this->saveHandler($handler);
			return $this->getHandler($classname);
		}

		if (is_object($tempHandler) && $tempHandler instanceof JFX_Module_Blockstyle_Handler) {
			$tempHandler->loadElements();
			JFX::register('JFX_Module_Blockstyle_Handler_' . $classname, $tempHandler);
			return $tempHandler;
		}

		if (!is_object($tempHandler)) {
			$tempHandler = new stdClass();
			if (!isset($tempHandler->elements)) {
				$tempHandler->elements = array();
			}
		}

		$handler = new JFX_Module_Blockstyle_Handler($classname);

		$handler->updateFromJson($tempHandler);
		$handler->loadElements();

		JFX::register('JFX_Module_Blockstyle_Handler_' . $classname, $handler);

		return $handler;
	}

	public function hasClassname($classname) {
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		return ($DB->countRows($CONFIG->dbprefix . $this->keyname . '_classnames', "classname = '{$classname}'") > 0);
	}

	public function serve() {
		$VIEW = JFX::registry('JFX_View');
		$SMARTY = JFX::registry('Smarty');
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$USER = JFX::registry('JFX_User');
		$CRYPT = JFX::registry('JFX_Crypt');
		$LINK = JFX::registry('JFX_Link');
		$THEME = JFX::registry('JFX_Theme');
		$CORE = JFX::registry('JFX_Core');
		$SETTINGS = JFX::registry('JFX_Settings');

		$req = explode('?', THIS_PAGE_URL);
		$requestedFile = str_replace($this->publicUrl, '', $req[0]);
		$requestedFile = str_replace('../', '/', $requestedFile);
		if (file_exists($this->dirname . '/public/' . $requestedFile . '.php')) {
			$SMARTY->assign('publicUrl', $this->publicUrl);
			include($this->dirname . '/public/' . $requestedFile . '.php');
		} else {
			$LINK->throw404();
			exit;
		}
	}

	public function getContent($params) {
		return '';
	}

	public function prepare($details) {
		return $this->getContent($details);
	}

	public function admin($url, $dirname) {
		//$this->resetLanguages();
		if (!$this->checkPermission('perm_manage_' . $this->keyname)) {
			JFX::addError($this->lang('not_permitted'));
			JFX::redirect($CONFIG->adminUrl);
		}

		$VIEW = JFX::registry('JFX_View');
		$SMARTY = JFX::registry('Smarty');
		$USER = JFX::registry('JFX_User');
		$CONFIG = JFX::registry('config');
		$DB = JFX::registry('db');
		$SMARTY->assign('actionUrl', $url);
		$LANG = JFX::registry('lang');
		$THEME = JFX::registry('JFX_Theme');
		$CORE = JFX::registry('JFX_Core');
		$SETTINGS = JFX::registry('JFX_Settings');

		$THEME->breadcrumbs[0]->set('icon', $this->imageUrl . '/brush.png');
		$THEME->addBreadcrumb($this->adminUrl, $this->getTitle());

		$urlParts = explode('?', $url);
		$urlParts = $urlParts[0];
		$urlParts = explode('/', trim(str_replace($this->adminUrl, '', $urlParts), '/'));

		$selectedTab = (string) array_shift($urlParts);
		if (trim($selectedTab) == '') {
			$selectedTab = 'edit';
		}

		$tabs = array(
		    array(
			'label' => 'new',
			'title' => $this->lang('new_tab'),
			'selected' => ($selectedTab == 'new'),
			'url' => $this->adminUrl . '/new/'
		    ),
		    array(
			'label' => 'edit',
			'title' => $this->lang('edit_tab'),
			'selected' => ($selectedTab == 'edit'),
			'url' => $this->adminUrl . '/edit/'
		    )/* ,
			  array(
			  'label' => 'publish',
			  'title' => $this->lang('publish_tab'),
			  'selected' => ($selectedTab=='publish'),
			  'url' => $this->adminUrl.'/publish/'
			  ) */
		);

		$SMARTY->assign('tabs', $tabs);
		echo $this->fetchTemplate('tabs.tpl');

		echo '<div id="admin-content">';
		if (trim($selectedTab) != '' && file_exists($this->dirname . '/actions/' . $selectedTab . '.php')) {
			require($this->dirname . '/actions/' . $selectedTab . '.php');
		}
		echo '</div>';
	}

	public function install() {
		$VIEW = JFX::registry('JFX_View');
		$SMARTY = JFX::registry('Smarty');
		$USER = JFX::registry('JFX_User');
		$CONFIG = JFX::registry('config');
		$DB = JFX::registry('db');
		$dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)) . '/install';
		include('install/install.php');
	}

	public function uninstall() {
		$VIEW = JFX::registry('JFX_View');
		$SMARTY = JFX::registry('Smarty');
		$USER = JFX::registry('JFX_User');
		$CONFIG = JFX::registry('config');
		$DB = JFX::registry('db');
		$dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)) . '/install';
		include('install/uninstall.php');
	}

}